package com.lanxi.nbpaytest.scheduler;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;
import com.lanxi.nbpaytest.Service.MailService;
import com.lanxi.nbpaytest.Service.PayService;
import com.lanxi.nbpaytest.TimeUtil;
import com.lanxi.nbpaytest.requestparam.AccountRequest;
import com.lanxi.nbpaytest.requestparam.QueryBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author mintaoyu
 * Date on 2020-04-20  10:27
 */
@Component
@Slf4j
public class MailScheduler {


    @Autowired
    PayService payService;

    @Autowired
    MailService mailService;

    @Value("${lx.mailOne}")
    private String mailOne;

    @Value("${lx.mailTwo}")
    private String mailTwo;

    @Value("${lx.mailThree}")
    private String mailThree;

    @Value("${lanxi.appid}")
    private String appId;

    @Value("${nb.reconciliationUrl}")
    private String reconciliationUrl;

    /**
     * 定时任务每天12点获取前一天的对账文件发送到指定邮箱
     */
    @Scheduled(cron = "0 0 13 * * ?")
    public void sendMail() {
        // 获取一天之前的日期
        String billDate = TimeUtil.getDateAgo(1);
        QueryBody queryBody = new QueryBody();
        AccountRequest request = new AccountRequest();
        request.setBillDate(billDate);
        request.setMerId("313331090089000");
        String body = JSON.toJSONString(request);
        payService.init();
        String signMsg = payService.sign(body);
        queryBody.setBody(body);
        queryBody.setSignMsg(signMsg);
        String querybodyJSON = JSON.toJSONString(queryBody);
        log.info("下载body" + querybodyJSON);
        List<ArrayList<String>> rows = payService.myPost(appId, reconciliationUrl, querybodyJSON);
        //通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter();
        //一次性写出内容，强制输出标题
        writer.write(rows, true);
        // 输出地址
        writer.setDestFile(new File(billDate + "对账单.xlsx"));
        writer.flush();
        // 关闭writer，释放内存
        writer.close();
        // 将邮件推送
        mailService.sendAttachmentsMail(mailOne, billDate + "对账单.xlsx", "对账单", billDate + "对账单.xlsx");
        mailService.sendAttachmentsMail(mailTwo, billDate + "对账单.xlsx", "对账单", billDate + "对账单.xlsx");
        mailService.sendAttachmentsMail(mailThree, billDate + "对账单.xlsx", "对账单", billDate + "对账单.xlsx");
    }
}
